#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#include "tftlcd.h"
#include "mpu6050.h"
#include "tftlcdglob.h"
#include "armsdkerr.h"

INT4 armDrvTftlcdEnable()
{
    if (tftlcdState == TRUE)
    {
        PRINTF("tftlcd is already enabled\n");
        return FAILURE;
    }

    PRINTF("enable tftlcd...\n");
    tftlcdFilefd = open(tftlcdDrvFile, O_RDWR);
    if(tftlcdFilefd < 0)
    {
        PRINTF("can't open file %s\r\n", tftlcdDrvFile);
        return FAILURE;
    }

    tftlcdState = TRUE;

    return SUCCESS;
}

BOOL armDrvTftlcdState()
{
    return tftlcdState;
}

INT4 armDrvTftlcdDisable()
{
    PRINTF("Tftlcd module disable ...\n");
    close(tftlcdFilefd); /* 关闭文件 */

    tftlcdState = FALSE;
    return SUCCESS;
}

INT4 armDrvTftlcdWriteChar(CHR data)
{
    UINT1 u1Data = data; /* 要执行的操作：打开或关闭 */
    INT4 i4Ret;

    if (tftlcdState == FALSE)
    {
        PRINTF("tftlcd is disabled\n");
        return FAILURE;
    }

    /* 向/dev/{dev}文件写入数据 */
    i4Ret = write(tftlcdFilefd, &u1Data, sizeof(UINT1));
    if(i4Ret < 0)
    {
        printf("driver Control Failed!\r\n");
        armDrvTftlcdDisable();
        return FAILURE;
    }

    return SUCCESS;
}

INT4 armDrvTftlcdWriteStr(CHR *pu1Str)
{
    INT4 i4Inc;
    for (i4Inc = 0; i4Inc < strlen(pu1Str); i4Inc ++)
    {
        armDrvTftlcdWriteChar(pu1Str[i4Inc]);
    }

    return SUCCESS;
}

INT4 armDrvTftlcdClear()
{
    return armDrvTftlcdWriteChar(0);
}

INT4 armDrvTftlcdNextPage()
{
    return armDrvTftlcdWriteChar(1);
}

INT4 armDrvTftlcdGetMpu6050(INT4 num)
{
    INT4 i4Ret;
    INT4 i4Inc;
    CHR tftlcdStr[64] = {0};
    mpu6050_data_t mpuData;
    MEMSET(&mpuData, 0, sizeof(mpu6050_data_t));

    if (tftlcdState == FALSE)
    {
        PRINTF("tftlcd is disabled\n");
        return FAILURE;
    }
    if (gmpuState == FALSE)
    {
        PRINTF("mpu6050 is disabled\n");
        return FAILURE;
    }

    for (i4Inc = 0; i4Inc < num; i4Inc ++)
    {
        armDrvMpu6050Get(&mpuData);

        sprintf(tftlcdStr, "yaw: %.2f°        ", mpuData.yaw);
        armDrvTftlcdWriteStr(tftlcdStr);
        armDrvTftlcdNextPage();

        sprintf(tftlcdStr, "pitch: %.2f°        ", mpuData.pitch);
        armDrvTftlcdWriteStr(tftlcdStr);
        armDrvTftlcdNextPage();

        sprintf(tftlcdStr, "roll: %.2f°        ", mpuData.roll);
        armDrvTftlcdWriteStr(tftlcdStr);
        armDrvTftlcdNextPage();
        /*sprintf(tftlcdStr + strlen(tftlcdStr), "temper: %.2f°",mpuData.temperature);*/
        /*MEMSET(tftlcdStr, 0, 64);*/
    }
    return SUCCESS;
}


